/*
Copyright (c) 2009, David A. Freels Sr.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package net.whippetcode.plugins.intellij.hudson;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.*;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.Content;
import com.intellij.peer.PeerFactory;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Timer;

import net.whippetcode.plugins.intellij.hudson.ui.HudsonDetailPanel;
import net.whippetcode.plugins.intellij.hudson.ui.StatusIndicator;
import net.whippetcode.plugins.intellij.hudson.job.Status;

/**
 * This is the main entry point.
 *
 * @author David A. Freels Sr.
 */
@State(name = "HudsonMonitorComponent",
	 storages = @Storage(id = "HudsonMonitorSettings", file = "$PROJECT_FILE$"))
public class HudsonMonitorComponent implements ProjectComponent, Configurable, PersistentStateComponent<HudsonMonitorSettings>
{
	public static final String TOOL_WINDOW_ID = "Hudson";

	private HudsonMonitorConfiguration form;
	private Project project;
	private StatusIndicator statusIndicator;
	private HudsonDetailPanel hudsonDetailPanel;
	private Timer timer;
	private HudsonMonitorSettings settings;
	private ImageIcon icon;
	private ImageIcon toolBarIcon;

	public HudsonMonitorComponent(Project project) throws Exception
	{
		this.project = project;
		statusIndicator = new StatusIndicator();
		hudsonDetailPanel = new HudsonDetailPanel();
		settings = new HudsonMonitorSettings();

		Image logo = ImageIO.read(this.getClass().getResourceAsStream("/net/whippetcode/plugins/intellij/hudson/images/hudson_logo.gif"));
		icon = new ImageIcon(logo);
		logo = ImageIO.read(this.getClass().getResourceAsStream("/net/whippetcode/plugins/intellij/hudson/images/hudson_logo_small.png"));
		toolBarIcon = new ImageIcon(logo);

		statusIndicator.updateTooltip("Not Initialized");
	}

	public void initComponent()
	{

	}

	public void disposeComponent()
	{
	}

	@NotNull
	public String getComponentName()
	{
		return "HudsonMonitorComponent";
	}

	@Nls
	public String getDisplayName()
	{
		return "Hudson Build Monitor";
	}

	public Icon getIcon()
	{
		return icon;
	}

	public String getHelpTopic()
	{
		return null;
	}

	public JComponent createComponent()
	{
		if (form == null)
		{
			form = new HudsonMonitorConfiguration();
		}
		return form.getRootPanel();
	}

	public boolean isModified()
	{
		return form != null && form.isModified(settings);
	}

	public void apply() throws ConfigurationException
	{
		if (form != null)
		{
			// Get data from form to component
			form.getData(settings);
			restartTimer();
		}
	}

	private void restartTimer()
	{
		if (settings.getServerAddress() == null)
		{
			return;
		}

		if (timer != null)
		{
			timer.cancel();
		}

		timer = new Timer();
		try
		{
			timer.schedule(new ServerPollingTask(settings, statusIndicator, hudsonDetailPanel, project), 0, Integer.parseInt(settings.getRefreshInterval()) * 60000);
		}
		catch (MalformedURLException e)
		{
			statusIndicator.updateStatus(Status.DISABLED);
			statusIndicator.updateTooltip(e.getMessage());
		}
		catch (URISyntaxException e)
		{
			statusIndicator.updateStatus(Status.DISABLED);
			statusIndicator.updateTooltip(e.getMessage());
		}
	}

	public void reset()
	{
		if (form != null)
		{
			// Reset form data from component
			form.setData(settings);
		}
	}

	public void disposeUIResources()
	{
		form = null;
	}

	public void projectOpened()
	{
		ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(this.project);
		ToolWindow toolWindow = toolWindowManager.registerToolWindow(TOOL_WINDOW_ID, false, ToolWindowAnchor.LEFT);

		ContentFactory contentFactory = PeerFactory.getInstance().getContentFactory();
		Content content = contentFactory.createContent(hudsonDetailPanel, "Hudson", false);
		toolWindow.getContentManager().addContent(content);
		toolWindow.setIcon(toolBarIcon);

		StatusBar sb = WindowManager.getInstance().getStatusBar(this.project);
		sb.addCustomIndicationComponent(statusIndicator);
		restartTimer();
	}

	public void projectClosed()
	{
		StatusBar sb = WindowManager.getInstance().getStatusBar(this.project);
		sb.removeCustomIndicationComponent(statusIndicator);
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}

		ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(this.project);
		toolWindowManager.unregisterToolWindow(TOOL_WINDOW_ID);
	}

	public HudsonMonitorSettings getState()
	{
		return settings;
	}

	public void loadState(HudsonMonitorSettings o)
	{
		XmlSerializerUtil.copyBean(o, settings);
	}
}
